import os
from utils import mongo_util, file_util

def download_temp_images(stu_no, filename, save_path):
    client, gridFS, file_list = mongo_util.get_file_list(filename, 'temp')
    index = 0
    for file in file_list:
        index += 1
        filename = save_path + stu_no + '_' + str(index) + '.jpg'
        with open(filename, 'wb+') as f:
            f.write(file.read())
            gridFS.delete(file._file['_id'])
    client.close()

def upload_align_images(stu_no, file_path):
    # delete the old record
    mongo_util.del_record({'stu_no': stu_no}, 'emb')
    file_list = os.listdir(file_path)
    param_list = list()
    for file in file_list:
        filename = file_path + file
        new_base64 = file_util.encode_base64(file_util.to_base64(filename))
        imgs = {
            'stu_no': stu_no,
            'base64': new_base64
        }
        param_list.append(imgs)
    mongo_util.insert_many(param_list, 'emb')

def upload_embedding_file(filename, filepath, bucket_name, delete):
    # delete the old file
    if delete:
        mongo_util.del_file({'filename':filename}, bucket_name)
    mongo_util.upload_file(filepath, filename, bucket_name)

def get_file_info(filename, bucket_name):
    return mongo_util.find_file(filename, bucket_name)

def download_file(save_path, file_info):
    with open(save_path, 'wb') as f:
        f.write(file_info.read())

def get_threshold(query, colle_name):
    return mongo_util.find_one(query, colle_name)

def remove_file(query, bucket_name):
    return mongo_util.del_file(query, bucket_name)
